package me.ingxin.android.view

import android.content.Context
import android.util.AttributeSet
import androidx.appcompat.widget.AppCompatImageView
import me.ingxin.android.R

/**
 * Created by ingxin on 2022/5/31
 */
class RatioImageView @JvmOverloads constructor(
    context: Context, attrs: AttributeSet? = null
) : AppCompatImageView(context, attrs) {

    /**宽高比*/
    private var ratio = 0f

    init {
        initViews(context, attrs)
    }

    private fun initViews(context: Context, attrs: AttributeSet?) {
        val a = context.obtainStyledAttributes(attrs, R.styleable.RatioImageView)
        ratio = a.getFloat(R.styleable.RatioImageView_riv_wh_ratio, 0f)
        a.recycle()
    }

    override fun onMeasure(widthMeasureSpec: Int, heightMeasureSpec: Int) {
        if (ratio > 0) {
            //设置默认尺寸
            setMeasuredDimension(
                getDefaultSize(0, widthMeasureSpec),
                getDefaultSize(0, heightMeasureSpec)
            )
            //通过宽度设置高度
            val widthSpec = MeasureSpec.makeMeasureSpec(measuredWidth, MeasureSpec.EXACTLY)
            val heightSpec =
                MeasureSpec.makeMeasureSpec((measuredWidth / ratio).toInt(), MeasureSpec.EXACTLY)
            super.onMeasure(widthSpec, heightSpec)
        } else {
            super.onMeasure(widthMeasureSpec, heightMeasureSpec)
        }
    }


}